﻿using Glorysoft.Auto.Xfw;
using Glorysoft.Auto.Xfw.Contract;
using Glorysoft.Auto.Xfw.Entities;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.RC.EAPClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Glorysoft.EAP.EC.Daemon.Tester
{
    public class DaemonTesterService : AbstractService
    {
        private readonly Logger CimLogger;
        protected readonly XfwContext Context = XfwContext.Current;
        protected readonly string conn = "1";
        protected readonly string disConn = "-1";
        EAPClientService ClientService = null;
        private DbService dbServer = null;
        public DaemonTesterService()
        {
            try
            {
                CimLogger = XfwContext.LogManager.EapLogger;
                ClientService = new EAPClientService();
                dbServer = new DbService();               
            }
            catch (Exception ex)
            {
                Logger.Error(ex, $"{Name}.DaemonTesterService() Execute Error.");
            }
        }
        public virtual string Name => GetType().Name;
        public string CurrentMethod => MethodBase.GetCurrentMethod().Name;
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="args"></param>
        public void Disconnect(XfwArgs args)
        {
            try
            {
                var eqpID = args.SECSData.Context.Name;
                args.Header[CItems.EqpStatus] = disConn;
                Dict.Current.DaemonName = eqpID;
                args.Header[CItems.EqpID] = eqpID;
            }
            catch (Exception e)
            {
                Logger.Error(e, $"{Name}.HsmsDisConnected() Execute Error.");
            }
        }

        /// <summary>
        /// 监控心跳
        /// </summary>
        /// <param name="args"></param>
        public void HeartBeat(XfwArgs args)
        {
            try
            {
                var ctx = args.JsonData.Context as IDaemonContext;
                var strVal = args.JsonData.SData;
                var json = XfwUtils.DeserializeObject<JObject>(strVal);
                args.Header[CItems.EqpID] = json.GetBody().GetVal("EqpID");
                args.Header[CItems.IsConnect] = json.GetBody().GetVal("IsConnect");
                var eqpID = args.Header[CItems.EqpID]?.ToString();
                args.Header[CItems.EqpStatus] = conn;
                if (!string.IsNullOrEmpty(eqpID))
                {
                    Dict.Current.DaemonName = eqpID;
                }
                if (args.Header[CItems.IsConnect]?.ToString() != Dict.Current.DaemonConnStatus)
                {
                    Dict.Current.DaemonConnStatus = "1";
                    var interval = 60;
                    if (!string.IsNullOrEmpty(Dict.Current.Interval))
                    {
                        interval = Convert.ToInt32(Dict.Current.Interval);
                    }
                    Scheduler.Add("SendHeartBeat", interval, ScheduleOptions.Loop, new Action<object>(obj => SendHeartBeat(args)), null);
                    dbServer.InsertMsgInfo("Daemon连接成功", eqpID, Dict.Current.lotInfo.lotId);

                }
                var eqpType = ctx.Configuration.EqpType;
                Dict.Current.TesterType = eqpType;
                args.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }

        /// <summary>
        /// 调用Daemon进行设备时间同步
        /// </summary>
        /// <param name="args"></param>
        public async void SyncTime(XfwArgs args)
        {
            try
            {
                var ctx = args.JsonData.Context as IDaemonContext;
                var strVal = args.JsonData.SData;
                var json = XfwUtils.DeserializeObject<JObject>(strVal);
                string eqpID = json.GetBody().GetVal("EqpID");
                var req = new Request() { Header = XfwUtils.CreateHeader("SyncTime") };
                req.Body.AddString(CItems.EqpID, eqpID);
                req.Body.AddString(CItems.Dtime, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //Console.WriteLine($"{DateTime.Now}:时间发送=>{ JsonConvert.SerializeObject(req)}");
                var resp = ctx.Request(req);
                //Console.WriteLine($"{DateTime.Now}:时间返回=>{ JsonConvert.SerializeObject(resp)}");
                args.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }
        /// <summary>
        /// 获取设备状态
        /// </summary>
        /// <param name="args"></param>
        public async void GetEqpStatus(XfwArgs args)
        {
            try
            {
                var ctx = args.JsonData.Context as IDaemonContext;
                var strVal = args.JsonData.SData;
                var json = XfwUtils.DeserializeObject<JObject>(strVal);
                string eqpID = json.GetBody().GetVal("EqpID");
                var req = new Request() { Header = XfwUtils.CreateHeader("GetEqpStatus") };
                req.Body.AddString(CItems.EqpID, eqpID);
                //Console.WriteLine($"{DateTime.Now}:状态发送=>{ JsonConvert.SerializeObject(req)}");
                var resp = ctx.Request(req);
                //Console.WriteLine($"{DateTime.Now}:状态返回=>{ JsonConvert.SerializeObject(resp)}");
                if (resp != null)
                {
                    args.Header[CItems.EqpStatus] = resp.Body.GetVal("EqpStatus");
                    args.Header[CItems.EqpID] = eqpID;
                    args.SetReturnCodeOK();
                }
                else
                {
                    args.SetReturnCodeNG($"状态返回:{resp}");
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }

        /// <summary>
        /// 发送:下载程序
        /// </summary>
        /// <param name="args"></param>
        public void Send_DownLoadTestProgram(XfwArgs args)
        {
            try
            {
               
                var eqpID = Dict.Current.TesterID; 
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpID, MessageType.Info, messages, MessageOrigin.Daemon);
                    args.SetReturnCodeNG($"{Name}.Send_DownLoadTestProgram() The EAP has been switched Automatic Operation");
                    return;
                }
                var lotid = args.Header[CItems.LotID]?.ToString();
                var operatorid = args.Header[CItems.UserName]?.ToString();
                args.Header[CItems.EqpID] = eqpID;
                ContextObject eqpcontexts = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpcontexts?.AllContexts[0] as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("DownLoadProgram") };
                req.Body.AddString(CItems.TesterEqpID, eqpID);
                req.Body.AddString(CItems.LotID, Dict.Current.lotInfo.lotId);  // args.Header[CItems.LotID]?.ToString()             
                req.Body.AddString(CItems.ProductID, Dict.Current.lotInfo.testerProgram.Trim()); // args.Header[CItems.TestProgram]?.ToString()
                req.Body.AddString(CItems.SortID, "CP1");
                req.Body.AddString(CItems.TestProgram, Dict.Current.lotInfo.testerProgram.Trim());
                req.Body.AddString(CItems.PIBID, CItems.PIBIDValue);
                req.Body.AddString(CItems.ProberCardIDLeft, Dict.Current.lotInfo.ProberCardId);//args.Header[CItems.ProberCardId]?.ToString()
                req.Body.AddString(CItems.ProberCardIDRight, "0000");
                req.Body.AddString(CItems.OperatorID, Dict.Current.lotInfo.userName);//args.Header[CItems.UserName]?.ToString()
                req.Body.AddString(CItems.RunModeSelected, "Production");
                var jstq = JsonConvert.SerializeObject(req);              
                var messagess = TranslateMsg.GetTranslation("SendDownRecipe");
                if (messagess != null && messagess.Count != 0)
                {
                    ClientService.ShowMessage(eqpID, MessageType.Info, messagess, MessageOrigin.Daemon);
                }
                var resp = ctx.Request(req);
                var jst = JsonConvert.SerializeObject(resp);

                //  Console.WriteLine($"{DateTime.Now}[DownLoadProgram]=>接收结果：[{jst}]");
                if (resp != null)
                {
                    if (resp.Return.ReturnCode == "0") //下载成功标识，按实际接口定义修改
                    {
                        args.Header[CItems.ReturnCode] = "0";
                        //提示Client 测试下载Recipe 成功
                        args.SetReturnCodeOK();
                        Dict.Current.TesterRunStatus = "1";
                        dbServer.InsertMsgInfo("发送DownLoadTes给Daemon，下载测试机Recipe成功", eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                    else
                    {
                        args.Header[CItems.ReturnCode] = "1";
                        args.Header[CItems.ReturnMessage] = resp.Return.ReturnMessage;
                        //提示Client 测试下载Recipe 失败
                        args.SetReturnCodeNG($"测试机下载Recipe失败");
                        dbServer.InsertMsgInfo("发送DownLoadTes给Daemon，下载测试机Recipe失败" + resp.Return.ReturnMessage, eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                }
                else
                {
                    args.Header[CItems.ReturnCode] = "2";
                    //提示Client 测试下载Recipe响应超时
                    args.SetReturnCodeNG($"测试机响应超时");
                    dbServer.InsertMsgInfo("发送DownLoadTes给Daemon，下载测试机Recipe失败，接口响应超时", eqpID, Dict.Current.lotInfo.lotId);
                    return;
                }
            }
            catch (Exception ex)
            {
                args.SetReturnCodeNG(ex.Message);
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }

        /// <summary>
        /// 发送：控制Tester测试结束
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void Send_EndTest(XfwArgs args)
        {
            try
            {
                var eqpID = Dict.Current.TesterID;
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpID, MessageType.Info, messages, MessageOrigin.Daemon);
                    args.SetReturnCodeNG($"{Name}.Send_EndTest() The EAP has been switched Automatic Operation");
                    return;
                }
                if (Dict.Current.TesterRunStatus == "0")
                {
                    CimLogger.Warning($"{CurrentMethod}.DownLoadTestProgramResult(): Test 已结束测试");
                    args.SetReturnCodeNG($"{Name}.DownLoadTestProgramResult(): Test 已结束测试");
                    return;
                }               
                args.Header[CItems.EqpID] = eqpID;
                var lotId = args.Header[CItems.LotID]?.ToString();
                var lotid = string.IsNullOrEmpty(lotId) ? Dict.Current.lotInfo.lotId : lotId;
                var userName = args.Header[CItems.UserName]?.ToString();
                var operatorid = string.IsNullOrEmpty(userName) ? Dict.Current.lotInfo.userName : userName;             
                ContextObject eqpcontexts = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpcontexts?.AllContexts[0] as IDaemonContext;
                //var ctx = args.JsonData.Context as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("EndTest") };
                JObject jObject = new JObject();
                jObject.AddString(CItems.TesterEqpID, eqpID);
                jObject.AddString(CItems.LotID, lotid);
                jObject.AddString(CItems.OperatorID, operatorid);
                req.Body = jObject;
                var messagess = TranslateMsg.GetTranslation("SendEndTest");
                if (messagess != null && messagess.Count != 0)
                {
                    ClientService.ShowMessage(eqpID, MessageType.Info, messagess, MessageOrigin.Daemon);
                }
                var resp = ctx.Request(req);
                var json = JsonConvert.SerializeObject(resp);
                Console.WriteLine($"{DateTime.Now.ToString(CItems.DateTimeFormat)}[json]=>收到回复：[{json}]");
                if (resp != null)
                {               
                    args.SetReturnCode(resp.Return.ReturnCode, resp.Return.ReturnMessage);
                    if (resp.Return.ReturnCode == "0") //EndTest 标识，按实际接口定义修改
                    {
                        args.Header[CItems.ReturnCode] = "0";
                        args.SetReturnCodeOK();
                        Dict.Current.TesterRunStatus = "0";
                        dbServer.InsertMsgInfo("发送EndTests给Daemon，关闭测试机程序成功", eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                    else
                    {
                        args.Header[CItems.ReturnCode] = "1";
                        args.Header[CItems.ReturnMessage] = resp.Return.ReturnMessage;
                        args.SetReturnCodeNG($"测试机End Test失败");
                        dbServer.InsertMsgInfo("发送EndTests给Daemon，关闭测试机程序失败 " + resp.Return.ReturnMessage, eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                }
                else
                {
                    args.Header[CItems.ReturnCode] = "2";
                    //提示Client 测试下载Recipe响应超时
                    args.SetReturnCodeNG($"测试机响应超时");
                    dbServer.InsertMsgInfo("发送EndTests给Daemon，关闭测试机程序失败，测试机响应超时", eqpID, Dict.Current.lotInfo.lotId);
                    return;
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{CurrentMethod}: {ex}");
                args.SetReturnCodeNG($"{CurrentMethod}: {ex}");
            }
        }


        /// <summary>
        /// amida测试机下载recipe daemon
        /// </summary>
        /// <param name="args"></param>
        public void Send_DownLoadTestProgramToAmida(XfwArgs args)
        {
            try
            {
                var eqpID = Dict.Current.TesterID; //args.Header[CItems.EqpID]?.ToString();
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpID, MessageType.Info, messages, MessageOrigin.Daemon);
                    args.SetReturnCodeNG($"{Name}.Send_DownLoadTestProgram() The EAP has been switched Automatic Operation");
                    return;
                }
                var lotid = args.Header[CItems.LotID]?.ToString();
                var operatorid = args.Header[CItems.UserName]?.ToString();
                args.Header[CItems.EqpID] = eqpID;
                ContextObject eqpcontexts = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpcontexts?.AllContexts[0] as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("DownLoadProgram") };
                req.Body.AddString(CItems.TesterEqpID, eqpID);
                req.Body.AddString(CItems.LotID, Dict.Current.lotInfo.lotId);  // args.Header[CItems.LotID]?.ToString()               
                req.Body.AddString(CItems.ProductID, Dict.Current.lotInfo.testerProgram); // args.Header[CItems.TestProgram]?.ToString()
                req.Body.AddString(CItems.SortID, "CP1");
                req.Body.AddString(CItems.TestProgram, Dict.Current.lotInfo.testerProgram);
                req.Body.AddString(CItems.PIBID, CItems.PIBIDValue);
                req.Body.AddString(CItems.ProberCardIDLeft, Dict.Current.lotInfo.ProberCardId);//args.Header[CItems.ProberCardId]?.ToString()
                req.Body.AddString(CItems.ProberCardIDRight, "0000");
                req.Body.AddString(CItems.OperatorID, Dict.Current.lotInfo.userName);//args.Header[CItems.UserName]?.ToString()
                req.Body.AddString(CItems.RunModeSelected, "Normal Test");
                var jstq = JsonConvert.SerializeObject(req);
                // Console.WriteLine($"{DateTime.Now}[DownLoadProgram]=>发送消息：[{jstq}]");
                var messagess = TranslateMsg.GetTranslation("SendDownRecipe");
                if (messagess != null && messagess.Count != 0)
                {
                    ClientService.ShowMessage(eqpID, MessageType.Info, messagess, MessageOrigin.Daemon);
                }
                var resp = ctx.Request(req);
                var jst = JsonConvert.SerializeObject(resp);

                //  Console.WriteLine($"{DateTime.Now}[DownLoadProgram]=>接收结果：[{jst}]");
                if (resp != null)
                {
                    //args.Header["PrgLocalFile"] = resp.Body.GetVal("PrgLocalFile") ?? "";
                    //args.SetReturnCode(resp.Return.ReturnCode, resp.Return.ReturnMessage);
                    if (resp.Return.ReturnCode == "0") //下载成功标识，按实际接口定义修改
                    {
                        args.Header[CItems.ReturnCode] = "0";
                        //提示Client 测试下载Recipe 成功
                        args.SetReturnCodeOK();
                        Dict.Current.TesterRunStatus = "1";
                        dbServer.InsertMsgInfo("发送DownLoadTest给Daemon，下载测试机Recipe成功", eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                    else
                    {
                        args.Header[CItems.ReturnCode] = "1";
                        args.Header[CItems.ReturnMessage] = resp.Return.ReturnMessage;
                        //提示Client 测试下载Recipe 失败
                        args.SetReturnCodeNG($"测试机下载Recipe失败");
                        dbServer.InsertMsgInfo("发送DownLoadTest给Daemon，下载测试机Recipe失败" + resp.Return.ReturnMessage, eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                }
                else
                {
                    args.Header[CItems.ReturnCode] = "2";
                    //提示Client 测试下载Recipe响应超时
                    args.SetReturnCodeNG($"测试机响应超时");
                    dbServer.InsertMsgInfo("发送DownLoadTes给Daemon，下载测试机Recipe失败，接口响应超时", eqpID, Dict.Current.lotInfo.lotId);
                    return;
                }
            }
            catch (Exception ex)
            {
                args.SetReturnCodeNG(ex.Message);
                CimLogger.Error($"{GetType().Name}: {ex}");
            }

        }
        /// <summary>
        /// amida测试机点击开始测试按钮-daemon
        /// </summary>
        /// <param name="args"></param>
        public void Send_StartTest(XfwArgs args)
        {
            try
            {
                var eqpID = Dict.Current.TesterID;
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpID, MessageType.Info, messages, MessageOrigin.Daemon);
                    args.SetReturnCodeNG($"{Name}.Send_StartTest() The EAP has been switched Automatic Operation");
                    return;
                }
                // var strVal = args.JsonData.SData;
                // var eqpID = args.Header[CItems.EqpID]?.ToString();
                args.Header[CItems.EqpID] = eqpID;
                var lotId = args.Header[CItems.LotID]?.ToString();
                var lotid = string.IsNullOrEmpty(lotId) ? Dict.Current.lotInfo.lotId : lotId;
                var userName = args.Header[CItems.UserName]?.ToString();
                var operatorid = string.IsNullOrEmpty(userName) ? Dict.Current.lotInfo.userName : userName;
                //  var testtype = args.Header[CItems.TestType]?.ToString();
                ContextObject eqpcontexts = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpcontexts?.AllContexts[0] as IDaemonContext;
                //var ctx = args.JsonData.Context as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("StartTest") };

                req.Body.AddString(CItems.TesterEqpID, eqpID);
                req.Body.AddString(CItems.LotID, Dict.Current.lotInfo.lotId);  // args.Header[CItems.LotID]?.ToString()                                   
                req.Body.AddString(CItems.OperatorID, Dict.Current.lotInfo.userName);//args.Header[CItems.UserName]?.ToString()

                //var jstq = JsonConvert.SerializeObject(req);
                //JObject jObject = new JObject();
                //jObject.AddString(CItems.TesterEqpID, eqpID);
                //jObject.AddString(CItems.LotID, lotid);
                //jObject.AddString(CItems.OperatorID, operatorid);
                ////jObject.AddString(CItems.TestType, testtype);
                //req.Body = jObject;                                        
                var messagess = TranslateMsg.GetTranslation("SendStartTest");
                if (messagess != null && messagess.Count != 0)
                {
                    ClientService.ShowMessage(eqpID, MessageType.Info, messagess, MessageOrigin.Daemon);
                }
                var resp = ctx.Request(req);
                var json = JsonConvert.SerializeObject(resp);
                //Console.WriteLine($"{DateTime.Now.ToString(CItems.DateTimeFormat)}[json]=>收到回复：[{json}]");
                if (resp != null)
                {
                    //args.Header["PrgLocalFile"] = resp.Body.GetVal("PrgLocalFile") ?? "";
                    //args.SetReturnCode(resp.Return.ReturnCode, resp.Return.ReturnMessage);                 
                    if (resp.Return.ReturnCode == "0") //StartTest 标识，按实际接口定义修改
                    {
                        args.Header[CItems.ReturnCode] = "0";
                        args.SetReturnCodeOK();
                        Dict.Current.TesterRunStatus = "1";
                        dbServer.InsertMsgInfo("发送StartTest给Daemon，测试机开始成功", eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                    else
                    {
                        args.Header[CItems.ReturnCode] = "1";
                        args.Header[CItems.ReturnMessage] = resp.Return.ReturnMessage;
                        args.SetReturnCodeNG($"测试机Start Test失败");
                        dbServer.InsertMsgInfo("发送StartTest给Daemon，测试机开始失败" + resp.Return.ReturnMessage, eqpID, Dict.Current.lotInfo.lotId);
                        return;
                    }
                }
                else
                {
                    args.Header[CItems.ReturnCode] = "2";
                    //提示Client 测试下载Recipe响应超时
                    args.SetReturnCodeNG($"测试机响应超时");
                    dbServer.InsertMsgInfo("发送StartTest给Daemon，测试机开始失败，测试机响应超时", eqpID, Dict.Current.lotInfo.lotId);
                    return;
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{CurrentMethod}: {ex}");
                args.SetReturnCodeNG($"{CurrentMethod}: {ex}");
            }
        }
        /// <summary>
        /// 保存并上传测试结果文件
        /// </summary>
        /// <param name="args"></param>
        public void UpLoadTestDatafile(XfwArgs args)
        {
            try
            {
                var obj = args.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal("TesterEqpID");
                var eqpConfig = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpConfig.AllContexts[0] as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("UpLoadTestDatafile") };
                req.Body.AddString("TesterEqpID", args.Header["TesterEqpID"].ToString());
                req.Body.AddString("LotID", args.Header["LotID"].ToString());
                req.Body.AddString("TestType", args.Header["TestType"].ToString());
                req.Body.AddString("StationID", args.Header["StationID"].ToString());
                req.Body.AddString("FTPServer", args.Header["FTPServer"].ToString());
                req.Body.AddString("FileName", args.Header["FileName"].ToString());
                req.Body.AddString("FilePath", args.Header["FilePath"].ToString());
                req.Body.AddString("FtpUser", args.Header["FtpUser"].ToString());
                req.Body.AddString("FtpPwd", args.Header["FtpPwd"]?.ToString());
                req.Body.AddString("FtpPort", args.Header["FtpPort"]?.ToString());
                var jstq = JsonConvert.SerializeObject(req);
                Console.WriteLine($"{DateTime.Now}[UpLoadTestDatafile]=>发送消息：[{jstq}]");
                var resp = ctx.Request(req);
                var jst = JsonConvert.SerializeObject(resp);
                Console.WriteLine($"{DateTime.Now}[UpLoadTestDatafile]=>接收结果：[{jst}]");
                if (resp != null)
                {
                    args.Header["DataFilename"] = resp.Body.GetVal("DataFilename") ?? "";
                    args.Header["FtpPath"] = resp.Body.GetVal("FtpPath") ?? "";
                    args.SetReturnCode(resp.Return.ReturnCode, resp.Return.ReturnMessage);
                }
                else
                {
                    args.SetReturnCodeNG($"测试机响应超时");
                }

            }
            catch (Exception ex)
            {
                args.SetReturnCodeNG(ex.Message);
                Logger.Error($"{GetType().Name}: {ex}");
            }

        }

        /// <summary>
        /// 下发设备控制命令
        /// RemoteType：1.连线，2.离线，3.锁机，4.解锁，5.停机
        /// </summary>
        /// <param name="args"></param>
        public void RemoteCommand(XfwArgs args)
        {
            try
            {
                var eqpID = args.Header[CItems.EqpID].ToString();
                var eqpConfig = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpConfig.AllContexts[0] as IDaemonContext;
                var commandName = args.Header["CommandName"].ToString();
                var req = new Request() { Header = XfwUtils.CreateHeader("RemoteCommand") };
                req.Body.AddString(CItems.EqpID, eqpID);
                req.Body.AddString("CommandName", commandName);
                var resp = ctx.Request(req);
                var jstq = JsonConvert.SerializeObject(req);
                Console.WriteLine($"{XfwUtils.GetTimeStamp()}[RemoteCommandSend]=>发送消息：[{jstq}]");
                var jst = JsonConvert.SerializeObject(resp);
                Console.WriteLine($"{XfwUtils.GetTimeStamp()}[RemoteCommandSend]=>接收结果：[{jst}]");
                args.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                args.SetReturnCodeNG(ex.Message);
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }

        #region Daemon上报事件
        /// <summary>
        /// EQP->EAP: EQP上报设备报警
        /// </summary>
        public void EqpAlarmReport(XfwArgs xfwArgs)
        {
            try
            {
                var strVal = xfwArgs.JsonData.SData;
                var json = XfwUtils.DeserializeObject<JObject>(strVal);
                xfwArgs.Header[CItems.EqpID] = json.GetBody().GetVal("EqpID");
                xfwArgs.Header[CItems.AlarmCode] = "128";
                xfwArgs.Header[CItems.AlarmID] = json.GetBody().GetVal("AlarmCode");
                xfwArgs.Header[CItems.AlarmMessage] = json.GetBody().GetVal("AlarmMessage");
                Console.WriteLine($"{XfwUtils.GetTimeStamp()}=>AlarmReport:{ xfwArgs.JsonData.Name},{json.ToString()},{json.GetVal("AlarmMessage")}");
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }

        /// <summary>
        /// EQP->EAP: EQP上报设备状态
        /// </summary>
        public void EqpStatuChangeReport(XfwArgs xfwArgs)
        {
            try
            {
                var strVal = xfwArgs.JsonData.SData;
                var json = XfwUtils.DeserializeObject<JObject>(strVal);
                string eqpId = json.GetBody().GetVal("EqpID");
                string eqpState = json.GetBody().GetVal("EqpStatus");
                xfwArgs.Header[CItems.EqpID] = eqpId;
                xfwArgs.Header[CItems.CurState] = eqpState;
                Console.WriteLine($"EQPReport：{eqpId},{eqpState}");
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }
        /// <summary>
        /// EQP->EAP: EQP上报设备事件
        /// </summary>
        public void EqpEventReport(XfwArgs xfwArgs)
        {
            try
            {
                var strVal = xfwArgs.JsonData.SData;
                var json = XfwUtils.DeserializeObject<JObject>(strVal);
                //xfwArgs.Header[CItems.EqpType] = EqpType;
                xfwArgs.Header[CItems.EqpID] = xfwArgs.JsonData.Name;
                xfwArgs.Header[CItems.EventName] = json.GetBody().GetVal("EventName");
                Console.WriteLine($"{XfwUtils.GetTimeStamp()}=>EventReport:{ xfwArgs.JsonData.Name},{ json.ToString()}");
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}: {ex}");
            }
        }

        #endregion


        /// <summary>
        /// 下载Recipe结果
        /// </summary>
        /// <param name="args"></param>
        public void DownLoadTestProgramResult(XfwArgs args)
        {
            try
            {
                var returnCode = args.Header[CItems.ReturnCode]?.ToString();
                var eqpID = Dict.Current.DaemonName;//args.Header[CItems.EqpID]?.ToString();
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpID, MessageType.Info, messages, MessageOrigin.Daemon);
                    args.SetReturnCodeNG($"{Name}.DownLoadTestProgramResult() The EAP has been switched Automatic Operation");
                    return;
                }
                if (Dict.Current.TesterRunStatus == "0")
                {
                    CimLogger.Warning($"{CurrentMethod}.DownLoadTestProgramResult(): Test 已结束测试");
                    args.SetReturnCodeNG($"{Name}.DownLoadTestProgramResult(): Test 已结束测试");
                    return;
                }
                args.Header[CItems.EqpID] = eqpID;
                args.Header[CItems.MessageOrigin] = MessageOrigin.Daemon.ToString();
                if (returnCode == "0") //下载成功
                {
                    args.Header[CItems.MessageType] = MessageType.Info.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.DownLoadTestOK);
                    args.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Warning($"{GetType().Name}.{nameof(EndTestResult)}: 下载recipe 成功");
                }
                else if (returnCode == "1")//下载失败
                {
                    var returnMsg = args.Header[CItems.ReturnMessage]?.ToString();
                    if (string.IsNullOrEmpty(returnMsg))
                    {
                        returnMsg = ".";
                    }
                    args.Header[CItems.MessageType] = MessageType.Error.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.DownLoadTestNG, returnMsg);
                    args.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Warning($"{GetType().Name}.{nameof(EndTestResult)}: 下载recipe 失败:{returnMsg}");
                }
                else//下载失败，Interface response timeout
                {
                    args.Header[CItems.MessageType] = MessageType.Error.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.DownLoadTestNG, "Interface response timeout");
                    args.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Warning($"{GetType().Name}.{nameof(EndTestResult)}: 下载recipe 失败-Interface response timeout");
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}.{nameof(DownLoadTestProgramResult)}: {ex}");
            }
        }

        /// <summary>
        /// Daemon EndTest 返回结果
        /// </summary>
        /// <param name="args"></param>
        public void EndTestResult(XfwArgs args)
        {
            try
            {
                var returnCode = args.Header[CItems.ReturnCode]?.ToString();
                var eqpID = Dict.Current.DaemonName;//args.Header[CItems.EqpID]?.ToString();
                if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
                {
                    var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                    ClientService.ShowMessage(eqpID, MessageType.Info, messages, MessageOrigin.Daemon);
                    args.SetReturnCodeNG($"{Name}.EndTestResult() The EAP has been switched Automatic Operation");
                    return;
                }             
                args.Header[CItems.EqpID] = eqpID;
                args.Header[CItems.MessageOrigin] = MessageOrigin.Daemon.ToString();
                if (returnCode == "0") //EndTest 成功
                {
                    args.Header[CItems.MessageType] = MessageType.Info.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.EndTestOK);
                    args.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Warning($"{GetType().Name}.{nameof(EndTestResult)}: End Test 成功");
                    var rptRunHisTemp = dbServer.SeleteRunHsiTemp(Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);
                    if (rptRunHisTemp != null)
                    {
                        if (string.IsNullOrEmpty(rptRunHisTemp.END_TIME))
                        {
                            rptRunHisTemp.END_TIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        }
                        //rptRunHisTemp.TRACKOUT_TIME = DateTime.Now.ToString();
                        dbServer.UpdateRunHsiTempByID(rptRunHisTemp);
                    }
                }
                else if (returnCode == "1")// EndTest 失败
                {
                    args.Header[CItems.MessageType] = MessageType.Error.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.EndTestNG);
                    args.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Warning($"{GetType().Name}.{nameof(EndTestResult)}: End Test 失败");
                }
                else//EndTest 失败，Interface response timeout
                {
                    args.Header[CItems.MessageType] = MessageType.Error.ToString();
                    Dictionary<string, string> msgs = TranslateMsg.GetTranslation(CItems.EndTestNG);
                    args.Header[CItems.TerminalMessage] = msgs;
                    CimLogger.Warning($"{GetType().Name}.{nameof(EndTestResult)}: End Test 失败-Interface response timeout");
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}.{nameof(EndTestResult)}: {ex}");
            }
        }

        public void SendHeartBeat(XfwArgs args)
        {
            try
            {
                var eqpID = Dict.Current.DaemonName;
                args.Header[CItems.EqpID] = eqpID;
                var ctx = args.JsonData.Context as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("HeartBeat") };
                JObject jObject = new JObject();
                jObject.AddString(CItems.TesterEqpID, eqpID);
                req.Body = jObject;
                var resp = ctx.Request(req);
                if (resp != null)
                {
                    args.SetReturnCode(resp.Return.ReturnCode, resp.Return.ReturnMessage);
                    if (resp.Return.ReturnCode == "OK")
                    {
                        args.Header[CItems.ReturnCode] = "0";
                        args.Header[CItems.EqpStatus] = conn;
                        args.SetReturnCodeOK();
                    }
                    else
                    {
                        args.Header[CItems.ReturnCode] = "1";
                        args.Header[CItems.EqpStatus] = disConn;
                        args.SetReturnCodeNG($"SendHeartBeat Daemon断开");

                    }
                }
                else
                {
                    args.Header[CItems.EqpStatus] = disConn;

                }
                ClientService.EqpStatusReport(args);
                //    Thread.Sleep(5000);
                //}
                var eqpType = ctx.Configuration.EqpType;
                Dict.Current.TesterType = eqpType;
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{CurrentMethod}: {ex}");
                args.Header[CItems.EqpStatus] = disConn;
            }
        }

        /// <summary>
        /// 发送自动和手动作业
        /// </summary>
        /// <param name="args"></param>
        public void SendAutoOrManualOperation(XfwArgs args)
        {
            try
            {
                var eqpID = Dict.Current.TesterID;
                // var strVal = args.JsonData.SData;
                //args.Header[CItems.EqpID] = eqpID;
                var testerMode = Convert.ToInt32(Dict.Current.EAPRunMode);
                var operatorid = args.Header[CItems.UserName]?.ToString();
                ContextObject eqpcontexts = Dict.Current.EqpConfigDic[eqpID];
                var ctx = eqpcontexts?.AllContexts[0] as IDaemonContext;
                var req = new Request() { Header = XfwUtils.CreateHeader("AutoOrManualOperation") };
                JObject jObject = new JObject();
                jObject.AddString(CItems.TesterEqpID, eqpID);
                jObject.AddString(CItems.OperationStatus, testerMode.ToString());
                jObject.AddString(CItems.OperatorID, operatorid);
                req.Body = jObject;
                var resp = ctx.Request(req);
                var json = JsonConvert.SerializeObject(resp);
                Console.WriteLine($"{DateTime.Now.ToString(CItems.DateTimeFormat)}[json]=>收到回复：[{json}]");
                if (resp != null)
                {
                    args.SetReturnCode(resp.Return.ReturnCode, resp.Return.ReturnMessage);
                    if (resp.Return.ReturnCode == "0")
                    {
                        args.Header[CItems.ReturnCode] = "0";
                        args.SetReturnCodeOK();
                        Dict.Current.TesterRunStatus = "0";
                        return;
                    }
                    else
                    {
                        args.Header[CItems.ReturnCode] = "1";
                        args.Header[CItems.ReturnMessage] = resp.Return.ReturnMessage;
                        args.SetReturnCodeNG($"测试机切换手动或者自动作业失败失败");
                        return;
                    }
                }
                else
                {
                    args.Header[CItems.ReturnCode] = "2";
                    //提示Client 测试下载Recipe响应超时
                    args.SetReturnCodeNG($"测试机响应超时");
                    return;
                }
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{CurrentMethod}: {ex}");
            }
        }
    }
}
